#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "utils.h"

int trim_right(char * buf) {
	int len = 0;
	len = strlen(buf);

	if (buf[len - 1] == '\n'
		|| buf[len - 1] == ' ') {
		buf[len - 1] = '\0';
	}

	return 0;
}

int get_one_line_from_file(const char * file_name, char * buf) {
	int ret = -1;
	FILE * fp = NULL;
	char buf_tmp[200] = {0};

	fp = fopen(file_name, "r");
	if (!fp) return ret;

	if (fgets(buf_tmp, 200, fp) != NULL) {
		strncpy(buf, buf_tmp, strlen(buf_tmp));
	}
	fclose(fp);

	ret = 0;

	return ret;
}

int get_data_from_file(const char * file_name, const char *pattern, char * buf) {
	int ret = -1;
	FILE * fp = NULL;
	char buf_tmp[200] = {0};

	fp = fopen(file_name, "r");
	if (!fp) return ret;
	while (fgets(buf_tmp, 200, fp) != NULL) {
		if (scanf(buf_tmp, pattern, buf) == 1) {
			break;
		}
	}
	fclose(fp);

	ret = 0;

	return ret;
}


int popen_cmd_no_buf(const char * cmd) {
	FILE * f = NULL;

	f = popen(cmd, "r");	
	if (!f) return -1;
	pclose(f);

	return 0;
}

int popen_cmd(const char * cmd, char * buf, int max_buf_len) {
	FILE * f = NULL;
	int nread = 0;

	f = popen(cmd, "r");	
	if (!f) return -1;
	nread = fread(buf, 1, max_buf_len, f);
	pclose(f);

	return nread;
}
